<!--
 * @Author: actor
 * @Date: 2023-11-13 15:42:06
 * @email: 395593455@qq.com
 * @LastEditors: actor
 * @LastEditTime: 2024-03-18 18:39:28
 * @FilePath: \i-hos-app\shared\emr\src\views\editer\EmrEditer.vue
 * @Description:  电子病历编辑主体页面
-->
<template>
  <el-container class="emr emr_content">
    <!-- 电子病历头部相关配置 -->
    <el-header class="emr_set" v-if="props.type == 'design'">
      <Toolbar @toFatherConfig="getHeadClickConfig" />
    </el-header>
    <el-container class="emr_container">
      <!-- 电子病历编辑器主体 -->
      <el-main class="emr_main">
        <div class="printBtnGroup" style="text-align: center" v-if="props.type == 'form' || props.type == 'readOnly'">
          <el-button @click="print('printPreview')">打印预览</el-button>
          <el-button @click="print('print')">直接打印</el-button>
          <el-button @click="() => expPdf()">导出PDF</el-button>
        </div>
        <EditPage :type="props.type" :tmplJson="props.docTempJson" :isPrint="isPrint" />
      </el-main>
      <!-- 电子病历侧边栏配置 -->
      <el-aside class="emr_aside" width="270px" v-if="props.type == 'design'">
        <Sidebar @toFatherConfig="getHeadClickConfig" />
      </el-aside>
    </el-container>
  </el-container>

  <!-- 自定义动态组件 -->
  <div v-show="showComponent" ref="refComponent">
    <keep-alive>
      <component v-if="!!componentName" :is="dialogComponents.get(componentName)" :key="componentName" />
    </keep-alive>
  </div>
</template>

<script setup lang="ts">
  import { ref, Ref, shallowRef, defineAsyncComponent, watch } from 'vue'
  import { ISetType, ISetPaperState, ISetPaper } from '../../interface/set'
  // 电子病历页面主要构成组件
  import Toolbar from './Toolbar.vue' // 电子病历头部配置组件
  import EditPage from './EditPage.vue' // 电子病历页面
  import Sidebar from './Sidebar.vue' // 电子病历侧边栏配置

  // 富文本编辑操作hooks
  import { useEdit } from '../../hooks/useEdit'
  // 组件插入hooks
  import { useInsertComponent } from '../../hooks/useInsertComponent'
  import { usePdfHtml } from '../../hooks/usePdfHtml'
  // 打印
  import { lodopFn } from '../../utils/index'
  // 电子病历配置数据
  import { usePaperSetStore } from '../../store/paperSet'
  // 自定义渲染组件
  import componentList from '../../store/componentSet'
  // type对应值的说明：'design': 可编辑，可设计（默认值）；'form'：使用版本，可简单编辑可编辑文档，不可设计；'readOnly'： 只可查阅，不可操作
  const props = withDefaults(
    defineProps<{
      type: string
      docTempJson: string
    }>(),
    {
      type: 'design',
      docTempJson: '',
    }
  )

  // 是否隐藏自定义组件
  let showComponent: Ref<boolean> = ref(false)
  let isPrint: Ref<boolean> = ref(false)
  // shallowRef (跳过proxy 代理组件)
  const componentName: Ref<string> = shallowRef('')
  const dialogComponents: Ref<Map<string, any>> = shallowRef(new Map<string, any>())
  // 异步加载组件
  for (let obj of componentList) {
    dialogComponents.value.set(obj._tp as string, defineAsyncComponent(obj._cw))
  }

  // 解构 store的配置数据
  const paperSetStore: ISetPaperState = usePaperSetStore()

  // 动态插入组件的节点
  const refComponent: Ref<HTMLElement | null> = ref(null)

  // 组件插入
  const insertComponent = (val?: any) => {
    // 计算获取富文本当中需要插入的组件是否加载完毕(组件异步加载的原因)
    var timer = setInterval(() => {
      // 向电子病历页面插入的组件
      let node = refComponent.value as HTMLElement
      let firstchild = node.firstElementChild as any
      if (firstchild == null || (!firstchild && !(firstchild as any).dataset)) return
      useInsertComponent(node, componentName.value, val)
      // 插入成功之后，清楚定时器
      clearInterval(timer)
    }, 500)
  }

  // 打印
  const print = (type: string): void => {
    isPrint.value = true
    setTimeout(() => {
      let headHtml = document.querySelector('#emr_page_head')?.innerHTML as string,
        bodyHtml = document.querySelector('#emr_page_body')?.innerHTML as string,
        footerHtml = document.querySelector('#emr_page_footer')?.innerHTML as string,
        paperSet = paperSetStore._emr_paper_set,
        params = [
          {
            innerHtml: headHtml + bodyHtml + footerHtml,
            paperConfig: {
              pageHeight: paperSet._h,
              pageWidth: paperSet._w,
              pageName: paperSet._n,
              pageOrientation: paperSet._orien,
              pageNumberSite: '正下方',
            },
          },
        ]
      lodopFn(params, type)
      setTimeout(() => {
        isPrint.value = false
      }, 2000)
    }, 500)
  }

  // 到處pdf
  const expPdf = () => {
    // isPrint.value = true
    usePdfHtml(document.getElementById('emr_page'), 'save')
    // setTimeout(()=>{
    //   isPrint.value = true
    // },2000)
  }

  // 获取操作头部子组件传的数据配置,并进行相应的操作
  const getHeadClickConfig = (type: string, flag: ISetType, val?: any) => {
    // 获取操作头部的配置，并设置自定义渲染组件
    if (flag._dropDown == undefined || !flag._dropDown) {
      showComponent.value = true
      componentName.value = flag._tp as string
    }
    // 根据点击头部的配置类型执行不同的操作
    if (type == 'edit') {
      // 富文本编辑
      useEdit(flag._tp as string, flag._tp?.includes('Color') ? (flag._def_col as string) : '')
      // eventAction(flag._tp as string, flag._tp?.includes('Color') ? (flag._def_col as string) : '', type as string, '')
    } else if (type == 'insertDown') {
      showComponent.value = false
      // 判断是不是直接插入的组件，还是有下拉选择项
      if (flag._dropDown != undefined || !!flag._dropDown) return
      // 组件插入
      insertComponent(val)
    } else if (type == 'print') {
      print(flag._tp == 'printPreview' ? 'printPreview' : 'print')
    } else if (type == 'exp') {
      expPdf()
    } else {
      // 展开页面设置弹层视图
      paperSetStore.$patch?.((state: ISetPaperState): void => {
        state._paper_visible = true
      })
    }
  }
  watch(
    (): any => props.docTempJson,
    (): void => {
      if (typeof props.docTempJson != 'string') return
      if (!!props.docTempJson && !!JSON.parse(props.docTempJson).paperSet) {
        paperSetStore.$patch?.((state: ISetPaperState): void => {
          let _emrPaperSet: ISetPaper = state._emr_paper_set
          let _tmplPaperSet: ISetPaper = JSON.parse(props.docTempJson).paperSet
          _emrPaperSet._n = _tmplPaperSet._n
          _emrPaperSet._w = _tmplPaperSet._w
          _emrPaperSet._h = _tmplPaperSet._h
          _emrPaperSet._orien_n = _tmplPaperSet._orien_n
          _emrPaperSet._orien = _tmplPaperSet._orien
          _emrPaperSet._e_n = _tmplPaperSet._e_n
          _emrPaperSet._e = _tmplPaperSet._e
          _emrPaperSet._t_e = _tmplPaperSet._t_e
          _emrPaperSet._b_e = _tmplPaperSet._b_e
          _emrPaperSet._r_e = _tmplPaperSet._r_e
          _emrPaperSet._l_e = _tmplPaperSet._l_e
        })
      }
    },
    { immediate: true, deep: true }
  )

  // 页眉页面内容
  const emrHeadHtml = (): string => {
    return (document.querySelector('#emr_page_head')?.firstChild as Element).innerHTML
  }
  // 正文页面内容
  const emrBodyHtml = (): string => {
    return (document.querySelector('#emr_page_body')?.firstChild as Element).innerHTML
  }
  // 正文页面内容
  const emrFooterHtml = (): string => {
    return (document.querySelector('#emr_page_footer')?.firstChild as Element).innerHTML
  }

  // 暴露当前组件的属性
  defineExpose({
    emrBodyHtml,
    emrHeadHtml,
    emrFooterHtml,
  })
</script>

<style lang="scss" scoped>
  .emr {
    background-color: #f5f5f5;
    &.isPrint {
      * {
        background-color: #fff !important;
      }
    }
  }
  .el-container,
  .emr_main {
    height: 100%;
  }
  .el-header {
    padding: 0;
    height: auto;
    // box-shadow: 0px 1px 3px #d3d3d3;
    background-color: transparent;
    z-index: 9;
  }
  .emr_main {
    overflow: auto;
    padding: 10px;
  }
  .el-aside {
    background: #efefef;
    box-shadow: 0 0 5px rgba(64, 158, 255, 0.4);
  }
  .emr_content {
    overflow: hidden;
  }

  :deep(.el-tabs__header) {
    margin: 0;
  }
  :deep(.el-tabs__item) {
    padding: 0 8px !important;
  }
  :deep(.el-tabs__content) {
    padding: 0;
    overflow: auto;
    .el-tab-pane {
      // display: flex;
      padding: 5px;
      width: 100%;
      overflow-x: auto;
      min-height: 32px;
    }
  }
  .markBlink {
    animation: blink 0.3s linear infinite;
    color: #ffffff !important;
  }
  @keyframes blink {
    from {
      background-color: #409eff;
      -webkit-box-shadow: 0 0 2px #333;
    }
    50% {
      background-color: #99cbff;
      -webkit-box-shadow: 0 0 4px #ffb515;
    }
    to {
      background-color: #409eff;
      -webkit-box-shadow: 0 0 2px #333;
    }
  }

  // 重置样式（放在公共样式文件中）
  // .el-popper.is-emr_popper{
  //   padding: 1px 6px;
  //   background: var(--el-color-primary);
  //   color: #fff;
  //   font-size: 10px;
  // }
  // .el-popper.is-emr_popper .el-popper__arrow::before {
  //   background: var(--el-color-primary);
  //   right: 0;
  // }
  // .emr_color_picker{
  //   margin-top: 8px;
  // }
  // .emr_color_picker .el-color-predefine .el-color-predefine__colors .el-color-predefine__color-selector{
  //   border:1px solid #dcdfe6;
  // }
</style>
